<?php

declare (strict_types=1);
namespace app\admin\controller;
use app\BaseController;
use app\admin\model\Menu as MenuModel;
use app\common\controller\Backend;
use think\facade\View;

class Menu extends Backend
{
    public function initialize() {
        parent::initialize();
        $this->_mod  = new \app\admin\model\Menu();
    }

    public function _before_index(){
        $list = $this->_mod->getTree(0);
        View::assign('list',$list);
    }


    public function _before_insert($data)
    {
        //检测分类是否存在
        if ($this->_mod->name_exists($data['name'], $data['pid'])) {
            return '菜单名称已经存在';
        }
    }

    public function _before_add(){
        $data = [];
        $menulist = $this->_mod->where(array('pid' => 0,'status' => 1))->select();
        $data['info']['pid'] = request()->get('pid')?request()->get('pid'):0;
        $data['menulist']= $menulist;
        View::assign($data);
    }

    public function _before_update($data){
        if ($this->_mod->name_exists($data['name'], $data['pid'], $data['id'])) {
            return error(0,'菜单名称已经存在','','add');
        }
    }

    public function _before_edit(){
        $menulist = $this->_mod->where(array('pid' => 0,'status' => 1))->select();
        $data['menulist']= $menulist;
        View::assign('menulist',$menulist);
    }

    public function _before_delete($ids) {
        $catecount = $this->_mod->whereIn('pid' ,$ids)->count();
        if ($catecount >= 1) {
            return '该分类下有子菜单，不能删除！';
        }
    }


}